package com.study.gank.ui.activity

import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.study.gank.R
import com.study.gank.bean.GankGoods
import com.study.gank.databinding.ActivityMainBinding
import com.study.gank.di.component.RandomModule
import com.study.gank.getMainComponent
import com.study.gank.mvp.contract.RandomContract
import com.study.gank.mvp.presenter.RandomPresenter
import com.study.gank.router.GankClientUri
import com.study.gank.router.GankRouter
import com.study.gank.ui.fragment.AndroidFragment
import com.study.gank.ui.fragment.FragmentHolder
import com.study.gank.ui.fragment.GirlFragment
import com.study.gank.ui.fragment.IOSFragment
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.net.URLDecoder
import java.net.URLEncoder
import javax.inject.Inject

class MainActivity : BaseBindingActivity<ActivityMainBinding>(), RandomContract.View {

    lateinit var mFragments: MutableList<Fragment>

    @Inject
    lateinit var mPresenter: RandomPresenter

    override fun createDataBinding(savedInstanceState: Bundle?): ActivityMainBinding =
        DataBindingUtil.setContentView(this, R.layout.activity_main)

    override fun initView() {
        initFragment()
        getMainComponent().buildRandomComponent(RandomModule(this)).inject(this)
        initViewPager()

        mBinding.floatingButton.onClick {
            mPresenter.getRandom("Android")
        }
    }

    private fun initViewPager() {
        mBinding.viewPager.apply {
            adapter = object : FragmentPagerAdapter(
                supportFragmentManager,
                BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            ) {
                override fun getCount() = mFragments.size

                override fun getItem(position: Int) = mFragments[position]

            }
            offscreenPageLimit = 4
        }

        mBinding.navigationView.setOnNavigationItemSelectedListener { item ->
            var tab = 0
            when (item.itemId) {
                R.id.menu_android -> tab = 0
                R.id.menu_ios -> tab = 1
                R.id.menu_girl -> tab = 2
                R.id.menu_about -> tab = 3
            }
            mBinding.viewPager.currentItem = tab
            false
        }
    }

    private fun initFragment() {
        mFragments = mutableListOf()
        mFragments.add(AndroidFragment.newInstance())
        mFragments.add(IOSFragment.newInstance())
        mFragments.add(GirlFragment.newInstance())
        mFragments.add(FragmentHolder())
    }

    override fun onShowRandom(goods: GankGoods) {
        GankRouter.router(this, URLDecoder.decode(goods.url, "utf-8"))
    }
}